package com.yzh.wanandroid.component.activity

import android.view.KeyEvent
import androidx.navigation.NavGraph
import com.yzh.core.navigation.NavHostFragment
import com.yzh.wanandroid.R
import com.yzh.wanandroid.base.MvvmActivity
import com.yzh.wanandroid.callback.FragmentKeyDownListener
import com.yzh.wanandroid.databinding.ActivityMainBinding
import com.yzh.wanandroid.vm.MainActivityVm


/**
 * 主页面
 */
class MainActivity : MvvmActivity<ActivityMainBinding, MainActivityVm>() {

    private val TAG = "MainActivity"

    private lateinit var host: NavHostFragment

    private var mFragmentKeyDownListener: FragmentKeyDownListener? = null

    fun setFragmentKeyDownListener(fragmentKeyDownListener: FragmentKeyDownListener) {
        this.mFragmentKeyDownListener = fragmentKeyDownListener
    }

    override fun getLayoutId() = R.layout.activity_main

    override fun initViewModel(): MainActivityVm = this.createViewModel()

    override fun initView() {
        host = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment? ?: return
        val navController = host.navController
//        // 动态加载，设置首页
        val navGraph: NavGraph = navController.navInflater.inflate(R.navigation.start_navigation)
        navController.graph = navGraph
    }

    fun getHostFragment() = host

    override fun initData() {

    }

    fun clearKeyDownListener() {
        mFragmentKeyDownListener = null
    }

    /**
     *  fragment返回事件
     *  修复web存在多级页面，点击返回键直接返回到列表fragment(效果：web页面退出干净之后再退回到列表fragment)
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (mFragmentKeyDownListener?.onKeyDown(host, keyCode, event) == true) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}